import { getTagsPageList } from "@/api/service";
export function getRangeDate(value) {
  let para = {};
  const start = new Date();
  const today = new Date();
  const filterTime = (val) => {
    return parseTime(val, "{y}-{m}-{d} {h}:{i}:{s}");
  };
  switch (value) {
    case "month": {
      para = {
        beginDate: filterTime(
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        ),
        endDate: filterTime(today),
      };
      break;
    }
    case "season": {
      para = {
        beginDate: filterTime(
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        ),
        endDate: filterTime(today),
      };
      break;
    }
    case "helf": {
      para = {
        beginDate: filterTime(
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
        ),
        endDate: filterTime(today),
      };
      break;
    }
    case "year": {
      para = {
        beginDate: filterTime(
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
        ),
        endDate: filterTime(today),
      };
      break;
    }
    default: {
      break;
    }
  }
  return para;
}
/**
 * 验证手机号码
 * @rule {(Object|string|number)}
 * @value {string}
 * @callback {Function}
 * @returns
 */
export function phoneValid(rule, value, callback) {
  var reg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (
    reg.test(value) ||
    value === "" ||
    value === null ||
    value === undefined
  ) {
    if (value === undefined) value = "";
    callback();
  } else {
    callback(new Error("请填写正确的手机号码"));
  }
}

/**
 * 验证邮箱
 * @rule {(Object|string|number)}
 * @value {string}
 * @callback {Function}
 * @returns
 */
export function emailValid(rule, value, callback) {
  var reg =
    /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
  if (
    reg.test(value) ||
    value === "" ||
    value === null ||
    value === undefined
  ) {
    if (value === undefined) value = "";
    callback();
  } else {
    callback(new Error("请填写正确的邮箱"));
  }
}

// 英文字符
export function isChartacter(rule, value, callback) {
  var reg = /^[A-Za-z]*[A-Za-z.]+[A-Za-z]*$/;
  if (!value) {
    callback(new Error("请输入主题名称"));
  } else if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("只能填写英文字母"));
  }
}

// 正整数
export function isPositiveInteger(rule, value, callback) {
  var reg = /^[1-9]\d*$/;
  if (!value) {
    callback(new Error("请输入正整数的频率"));
  } else if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("只能填写正整数"));
  }
}

/**
 * 获得界面标签
 * @tagIdList {Array}
 * @returns
 */
export function getTagListById(tagIdList) {
  const tagList = getTagsPageList();
  const tagNameList = [];
  tagIdList.map((id) => {
    const I = tagList.findIndex((item) => item.id === id);
    if (I != -1) {
      tagNameList.push(tagList[I].label);
    }
  });
  return tagNameList.join("、");
}

// 校验JSON格式
export function isJSON(str) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log("error：" + str + "!!!" + e);
      return false;
    }
  }
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * 时间长度美化
 * @param {*} duration 时间长度
 * @param {*} type 时间单位 默认为ms 可填s
 * @returns
 */
export function simpleDuration(duration, type) {
  if (type === "s") {
    duration = duration * 1000;
  }
  let days = "",
    hours = "",
    minutes = "",
    seconds = "";
  let day = 24 * 60 * 60 * 1000,
    hour = 60 * 60 * 1000,
    minute = 60 * 1000,
    second = 1000;
  if (duration >= day) {
    days = Math.floor(duration / day) + "天";
    hours = Math.floor((duration % day) / hour) + "小时";
  } else if (duration >= hour && duration < day) {
    hours = Math.floor(duration / hour) + "小时";
    minutes = Math.floor((duration % hour) / minute) + "分钟";
  } else if (duration > minute && duration < hour) {
    minutes = Math.floor(duration / minute) + "分钟";
    seconds = Math.floor((duration % minute) / second) + "秒";
  } else if (duration <= minute && duration >= 1000) {
    seconds = Math.floor(duration / second) + "秒";
  } else {
    seconds = duration + "毫秒";
  }
  return days + hours + minutes + seconds;
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * download file
 * @param {response} 接收http返回的信息
 */
export function convertRes2Blob(response, title) {
  // 提取文件名
  const fileName = title;
  // 将二进制流转为blob
  const blob = new Blob([response.data]);
  if (typeof window.navigator.msSaveBlob !== "undefined") {
    // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
    window.navigator.msSaveBlob(blob, decodeURI(fileName));
  } else {
    // 创建新的URL并指向File对象s或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob);
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = blobURL;
    tempLink.setAttribute("download", decodeURI(fileName));
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    // 挂载a标签
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL);
  }
}

/**
 * contentd导出数据,fileName文件名
 */
export function exportDownload(content, fileName) {
  const blob = new Blob([content], {
    type: "application/vnd.ms-excel;charset=utf-8",
  }); // 构造一个blob对象来处理数据
  if ("download" in document.createElement("a")) {
    // 支持a标签download的浏览器
    const link = document.createElement("a"); // 创建a标签
    link.download = fileName; // a标签添加属性导出文件名
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    document.body.appendChild(link);
    link.click(); // 执行下载
    URL.revokeObjectURL(link.href); // 释放url
    document.body.removeChild(link); // 释放标签
  } else {
    // 其他浏览器
    navigator.msSaveBlob(blob, fileName);
  }
}

/**
 * 将以base64的图片url数据转换为Blob文件格式
 * @param urlData 用url方式表示的base64图片
 */
export function convertBase64UrlToBlob(urlData) {
  var bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
  //处理异常,将ascii码小于0的转换为大于0
  var ab = new ArrayBuffer(bytes.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: "image/png",
  });
}
/**
 * 获取中文序号 只支持99999以内
 * @param {nunber} index 序号
 * @return {string} 中文序号
 */
export function getChineseIndex(index) {
  const arr1 = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
  const arr2 = ["", "十", "百", "千", "万"];

  const strIndex = index.toString().split("").reverse();
  let res = "";
  for (let i = 0; i < strIndex.length; i++) {
    res = arr1[strIndex[i]] + arr2[i] + res;
  }

  if (res.indexOf("一十") === 0) {
    res = res.slice(1, res.length);
  }

  return res;
}

export { default as arraybuffer2html } from "./arraybuffer2html";

// export {
//   default as deriveword
// }
// from './deriveword'

export function isPhone() {
  if (
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    )
  ) {
    return true;
  }
  return false;
}

export function isSameDay(startTime, endTime) {
  const startTimeMs = new Date(startTime).setHours(0, 0, 0, 0);
  const endTimeMs = new Date(endTime).setHours(0, 0, 0, 0);
  return startTimeMs === endTimeMs ? true : false;
}

// 对象转查询字符串
export function objToQueryString(obj) {
  var queryString = "";
  for (var [key, item] of Object.entries(obj)) {
    queryString += key + "=" + item + "&";
  }

  queryString = queryString.replace(/&$/, ""); // 最后加上的 & 符号 去掉
  return queryString;
}
// 查询字符串转对象
export function queryStringToObj(strDes, delimiter) {
  var obj = {};
  if (strDes == null || strDes == "") {
    return obj;
  }
  delimiter = delimiter || ";";
  var arr = strDes.split(delimiter);
  var k, v, sub;
  for (var i = 0, len = arr.length; i < len; i++) {
    if (arr[i] !== "") {
      sub = arr[i].split("=");
      k = sub[0];
      v = sub[1];
      if (k !== "") {
        obj[k] = v;
      }
    }
  }
  return obj;
}
// 数组转字符串
export function arrToStr(arr) {
  let str = "";
  if (arr) {
    str = arr.join(";");
  }
  return str;
}

// JSON格式化
export function syntaxHighlight(json) {
  if (json) {
    if (typeof json !== "string") {
      json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    return json.replace(
      /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
      function (match) {
        var cls = "number";
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = "key";
          } else {
            cls = "string";
          }
        } else if (/true|false/.test(match)) {
          cls = "boolean";
        } else if (/null/.test(match)) {
          cls = "null";
        }
        return '<span class="' + cls + '">' + match + "</span>";
      }
    );
  }
}

// 状态码
export let statusCode = {
  ["C"]: "草稿",
  ["D"]: "已下线",
  ["A"]: "已上线",
};

export let auditCode = {
  ["T"]: "草稿",
  ["P"]: "待审核",
  ["A"]: "已审核",
  ["D"]: "已作废",
};

export function StatusCode(code, statusCode) {
  let name = "";
  statusCode.map((item) => {
    if (code == item.code) {
      name = item.codeLabel;
    }
  });
  return name;
}

// 上线状态码
export function cStatusCode(code) {
  return StatusCode(code, statusCode);
}
// 审核状态码
export function aStatusCode(code) {
  return StatusCode(code, auditCode);
}

export const httpStatusCode = {
  ["200"]: "200(正常)",
  ["300"]: "300(业务错误)",
  ["400"]: "400(请求错误)",
  ["401"]: "401(未授权)",
  ["403"]: "403(禁止)",
  ["404"]: "404(未找到)",
  ["500"]: "500(内部错误)",
};
// 所属应用名称转化
export function appNameChange(id, arr) {
  let name = "";
  arr.map((item) => {
    if (id == item.id) {
      name = item.appName;
    }
  });
  return name;
}

//  方法下载
export function fetchDownload(res) {
  let blobData = [res.data];
  let a = document.createElement("a");
  let url = window.URL.createObjectURL(new Blob(blobData)); // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
  console.log(res.headers["content-disposition"].split("=")[1]);
  let filename = window.decodeURI(
    res.headers["content-disposition"].split("=")[1]
  ); // 获取文件名并处理文件名编码问题
  filename = filename.replace("utf-8'zh_cn'", "");
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
}

// 判断对象属性值是否为空;
let hasOwn = Object.prototype.hasOwnProperty;
export function objIsAttr(obj, key) {
  return hasOwn.call(obj, key) && !!obj[key];
}

// html普通字符转换成转意符
export function html2Escape(sHtml) {
  if (typeof sHtml.data == "string") {
    sHtml.data = sHtml.data.replace(/[<>]/g, function (c) {
      return { "<": "&lt;", ">": "&gt;" }[c];
    });
  }
  try {
    sHtml.data = JSON.parse(sHtml.data);
  } catch {
    sHtml.data = sHtml.data;
  }
  return sHtml.data || "null";
}

// 查找值过滤数组
export const filtersArrey = (list, key, value) => {
  let tempList = [];
  list.map((item) => {
    if (item[key] == value) {
      tempList.push(item);
    }
  });
  return tempList;
};

// 查找id对应label值
export const FindArrey = (list, id, label, value) => {
  // console.log(list, id, label, value);
  let tempStr = "";
  list.map((item) => {
    if (item[id] == value) {
      tempStr = item[label];
    }
  });
  return tempStr;
};

export function obj2String(obj) {
  if (obj) {
    return JSON.stringify(obj);
  } else {
    return "";
  }
}
export function string2obj(str) {
  if (typeof str == "string" && str) {
    return JSON.parse(str);
  } else {
    return { header: [], queryParam: [], body: [] };
  }
}

export function string2Arr(str) {
  if (typeof str == "string" && str) {
    return JSON.parse(str);
  } else {
    return [];
  }
}

export function arr2StringJoinIndex(arr) {
  if (arr) {
    arr.map((item, index) => {
      item.index = index + 1;
    });
    return JSON.stringify(arr);
  } else {
    return "";
  }
}

export function funDownload(url, filename) {
  // 创建隐藏的可下载链接

  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
}

// 参数类型
export const paramType = [
  "text",
  "int",
  "double",
  "object",
  "list",
  "datetime",
  "boolean",
];

export const sqlParamType = [
  "STRING",
  "INT",
  "DOUBLE",
  "DATE",
  "BOOLEAN",
  "CURSOR",
];

// 文本下载
export function downloadTXT(filename, text) {
  var element = document.createElement("a");
  element.setAttribute(
    "href",
    "data:text/plain;charset=utf-8," + encodeURIComponent(text)
  );
  element.setAttribute("download", filename);
  element.style.display = "none";
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

// 取超链接最后的名称
export function queryLastName(strUrl) {
  return strUrl ? strUrl.substring(strUrl.lastIndexOf("/") + 1) : "";
}

// 生成数组 [0,1,2,3,..]
export function createArray(length) {
  return Array.from({ length }, (v, k) => k);
}

export function getTimestamp() {
  return Date.parse(new Date());
}
